const { User } = require("../model");

exports.showLogin = async (req, res, next) => {
  try {
    res.render("login.html", {
      isLogin: true,
    });
  } catch (error) {
    next(error);
  }
};

exports.login = async (req, res, next) => {
  try {
    const user = req.user;
    req.session.user = user;
    res.status(200).json({
      user,
    });
  } catch (error) {
    next(error);
  }
};

exports.showRegister = async (req, res, next) => {
  try {
    res.render("login.html");
  } catch (error) {
    next(error);
  }
};

exports.register = async (req, res, next) => {
  try {
    let user = new User(req.body.user);
    await user.save();
    req.session.user = user;
    res.status(200).json({
      user,
    });
  } catch (error) {
    next(error);
  }
};

exports.showSettings = async (req, res, next) => {
  try {
    res.render("settings.html");
  } catch (error) {
    next(error);
  }
};

exports.updateSettings = async (req, res, next) => {
  try {
    let user = req.session.user;
    let bodyUser = req.body.user;
    user.username = bodyUser.username || user.username;
    user.email = bodyUser.email || user.email;
    user.bio = bodyUser.bio || user.bio;
    user.image = bodyUser.image || user.image;
    user.password = bodyUser.password || user.password;
    console.log(user, bodyUser);
    await User.findByIdAndUpdate(user._id, user);
    req.session.destroy();
    res.status(200).json({
      user,
    });
  } catch (error) {
    next(error);
  }
};

exports.showProfile = async (req, res, next) => {
  try {
    res.render("profile.html");
  } catch (error) {
    next(error);
  }
};

exports.logout = async (req, res, next) => {
  try {
    req.session.user = null;
    res.redirect("/");
  } catch (error) {
    next(error);
  }
};
